package com.gopay.bis.service.bank.impl.ebank;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.bis.common.util.constants.BisPayConstants;
import com.gopay.bis.manager.bank.ebank.HnaPayManager;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.HnaPayConstants;
import com.gopay.common.constants.bank.HnaPayOrderStatus;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.hnapay.ebank.HnaPayMessage;
import com.gopay.common.domain.bank.hnapay.ebank.query.HnaPayMessageQuery;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.MoneyUtil;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * 新生在线网银直连业务实现类
 * 
 * @HnaPayBankServiceImpl.java
 * @author LiLiLi
 *
 */
public class HnaPayBankServiceImpl implements BankInteractRemoteService {

	@Resource(name = "hnaPayManager")
	HnaPayManager hnaPayManager;
	
	@Override
	public Result pay(BaseMessage base) {
		Result result = new Result(false);
		HnaPayMessage message = new HnaPayMessage();
		BeanUtils.copyProperties(base, message);
		try{
			message = (HnaPayMessage)hnaPayManager.sign(message);
	        result.setDefaultModel(message);
	        result.setSuccess(true);	
		}catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
    		result.setResultCode(e.getErrCode());
		}catch(Exception ex){
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6029);
		}
        return result;
	}

	@Override
	public Result bankBack(BaseMessage base) {
		Result result = new Result(false);
		HnaPayMessage message = new HnaPayMessage();
		BeanUtils.copyProperties(base, message);	
		try{
			boolean flag = (Boolean)hnaPayManager.verify(message);
			result.setModel("res", message);
            result.setDefaultModel(flag);
            result.setSuccess(true);
            String amount = base.getAmount().toString();
        	amount = MoneyUtil.formatAmt(amount);
        	if ((Boolean) result.getDefaultModel()) {
	        	if(message.getStateCode() != null && message.getStateCode().equals(HnaPayConstants.ORDER_STATE_SUCCESS)){
	                // 如果该订单成功通知后台地址入账
	                Map<String, String> param = new HashMap<String, String>();
	                param.put("orderId", base.getOrderId());
	                param.put("amt", amount);
	                param.put("cardType", "Unknown");
	                param.put("notifyNum", "1");
	                param.put("payStatus", "00");
	                param.put("retCode", "00");
	                param.put("retMsg", "");
	                param.put("signData", message.getSignMessage());
	                param.put("isFront", String.valueOf(base.isFront()));
	                result.setModel("isNotifyCashier", param);
	                result.setOrderStatus(true);
	                }
				else{
		             // 通知后台地址该订单失败
		             Map<String, String> param = new HashMap<String, String>();
		             param.put("orderId", base.getOrderId());
		             param.put("amt", amount);
		             param.put("cardType", "Unknown");
		             param.put("notifyNum", "1");
		             param.put("payStatus", "01");
		             param.put("retCode", "01");
		             param.put("retMsg", "");
		             param.put("signData", message.getSignMessage());
		             param.put("isFront", String.valueOf(base.isFront()));
		             result.setModel("isNotifyCashier", param);
		             result.setOrderStatus(false);
		     	}
        	}
        
           
    	}catch(GopayException e){
    		BankLogUtils.printServiceImplExceptionLog(e);
    		result.setResultCode(e.getErrCode());
    	}catch(Exception ex){
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
		}
		 return result;
	}

	@Override
	public Result query(BaseMessage base) {
		Result result = new Result(false);
		HnaPayMessageQuery message = new HnaPayMessageQuery();
		BeanUtils.copyProperties(base, message);
		try{
			message = (HnaPayMessageQuery)hnaPayManager.query(message);
            result.setDefaultModel(message);
            result.setSuccess(true);
            if(BisPayCheckUtils.checkExternalOrderID(base.getOrderId())){
        		Map<String, String> param = new HashMap<String, String>();
                String amount = base.getAmount().toString();
            	amount = MoneyUtil.formatAmt(amount);
        		param.put("orderId", base.getOrderId());
        		param.put("amount", amount);
        		if (message == null) {
		            // 查询订单为空
        			param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
        			param.put("returnMessage", "银行返回对账结果为空");
        			param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					result.setModel("queryResult", param);
					return result;
		        }
	
		        if (!StringUtils.equals(HnaPayConstants.TRADE_RETURN_SUCCESS, message.getResultCode())) {
        			// 查询订单错误
        			param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
        			param.put("returnMessage", "银行返回订单查询失败");
        			param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
					result.setModel("queryResult", param);
					return result;
		        }
	
		        if(message.getStateCode() != null&& HnaPayConstants.TRADE_RETURN_SUCCESS.equals(message.getResultCode())){
    				param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
		        	
		        	String[] arrayQuery = message.getQueryDetails().split(",");
					
		               message.setOrderId(arrayQuery[0]);
		               message.setOrderAmount(arrayQuery[1]);
		               message.setPayAmount(arrayQuery[2]);
		               message.setAcquiringTime(arrayQuery[3]);
		               message.setCompleteTime(arrayQuery[4]);
		               message.setOrderNo(arrayQuery[5]);
		               message.setStateCode(arrayQuery[6]);
			        // 判断交易订单处理状态
			        if (HnaPayConstants.ORDER_STATE_SUCCESS.equals(message.getStateCode())) {
						param.put("tradeState", BisPayConstants.TRADESTATE_SUCCESS);
						param.put("returnMessage", "交易成功");		            
			        } else if(StringUtils.equals(HnaPayConstants.ORDER_STATE_FAILURE, message.getStateCode())){
			        	 // 银行订单状态为失败
						param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
			            String errMsg = HnaPayOrderStatus.getName(message.getStateCode());
			            if (errMsg != null) {
							param.put("returnMessage", errMsg);
			            } else {
							param.put("returnMessage", "对账成功，银行返回交易失败");
			            }
			        }else if(StringUtils.equals(HnaPayConstants.ORDER_STATE_ACCEPT, message.getStateCode())){
			        	 // 银行查询交易已接受
						param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
			            String errMsg = HnaPayOrderStatus.getName(message.getStateCode());
			            if (errMsg != null) {
							param.put("returnMessage", errMsg);
			            } else {
							param.put("returnMessage", "对账成功，银行返回已接受");
			            }
			        }else if(StringUtils.equals(HnaPayConstants.ORDER_STATE_DEALING, message.getStateCode())){
			        	 // 银行查询交易处理中
			        	param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
			            String errMsg = HnaPayOrderStatus.getName(message.getStateCode());
			            if (errMsg != null) {
							param.put("returnMessage", errMsg);
			            } else {
							param.put("returnMessage", "对账成功，银行返回交易处理中");
			            }
			        }else {
			            // 银行订单状态未知
			        	param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
						param.put("returnMessage", "对账成功，银行返回交易未知");	
			        }
		        }// 没有查到订单
				else {
    				param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
        			param.put("returnMessage", "银行返回订单未查到");
        			param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
				}
        		result.setModel("queryResult", param);
        	}
		}catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
    		result.setResultCode(e.getErrCode());
		}catch(Exception ex){
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6033);
		}
		 return result;
	}

	@Override
	public Result refund(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result dayend(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result queryBack(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

    @Override
    public Result refundBack(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Result refundQuery(BaseMessage base) {
        // TODO Auto-generated method stub
        return null;
    }

	@Override
	public Result sendBankRefund(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

}
